package cn.com.cetccst.uicomponents.binding.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.databinding.BindingAdapter;
import androidx.databinding.InverseBindingAdapter;
import androidx.databinding.InverseBindingListener;

import cn.com.cetccst.uicomponents.R;

//自定义用户中心修改表单
public class FormFieldView extends LinearLayout {

    private TextView tvLabel;
    private EditText etInput;
    private Spinner spinner;

    private String label;
    private int fieldType;
    private String value;
    private boolean editable;
    private int spinnerEntriesResId;
    private float labelWidth;
    private String hint;

    public FormFieldView(Context context) {
        super(context);
        init(context, null);
    }

    public FormFieldView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public FormFieldView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.form_field_item, this, true);

        tvLabel = findViewById(R.id.tvLabel);
        etInput = findViewById(R.id.etInput);
        spinner = findViewById(R.id.spinner);

        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FormFieldView);

            label = a.getString(R.styleable.FormFieldView_ff_label);
            fieldType = a.getInt(R.styleable.FormFieldView_ff_fieldType, 0);
            value = a.getString(R.styleable.FormFieldView_ff_value);
            editable = a.getBoolean(R.styleable.FormFieldView_ff_editable, true);
            spinnerEntriesResId = a.getResourceId(R.styleable.FormFieldView_ff_spinnerEntries, 0);
            labelWidth = a.getDimension(R.styleable.FormFieldView_ff_labelWidth, -1);
            hint = a.getString(R.styleable.FormFieldView_ff_hint);

            a.recycle();
        }

        applyAttributes();
    }

    private void applyAttributes() {
        if (label != null) {
            tvLabel.setText(label);
        }

        if (labelWidth > 0) {
            LayoutParams params = (LayoutParams) tvLabel.getLayoutParams();
            params.width = (int) labelWidth;
            tvLabel.setLayoutParams(params);
        }

        if (fieldType == 0) { // 输入框
            etInput.setVisibility(VISIBLE);
            spinner.setVisibility(GONE);

            if (value != null) {
                etInput.setText(value);
            }

            etInput.setEnabled(editable);
            etInput.setFocusable(editable);
            etInput.setFocusableInTouchMode(editable);

            if (hint != null) {
                etInput.setHint(hint);
            }

        } else {
            etInput.setVisibility(GONE);
            spinner.setVisibility(VISIBLE);

            if (spinnerEntriesResId != 0) {
                ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                        getContext(),
                        spinnerEntriesResId,
                        android.R.layout.simple_spinner_item
                );
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);
                
                if (value != null) {
                    for (int i = 0; i < adapter.getCount(); i++) {
                        if (adapter.getItem(i).toString().equals(value)) {
                            spinner.setSelection(i);
                            break;
                        }
                    }
                }
            }

            spinner.setEnabled(editable);
        }
    }

    // 获取输入值
    public String getValue() {
        if (fieldType == 0) {
            return etInput.getText().toString();
        } else {
            return spinner.getSelectedItem().toString();
        }
    }

    // 双向绑定
    @BindingAdapter("value")
    public static void setValue(FormFieldView view, String value) {
        view.setValue(value);
    }

    @InverseBindingAdapter(attribute = "value", event = "valueChanged")
    public static String getValue(FormFieldView view) {
        return view.getValue();
    }

    @BindingAdapter("valueChanged")
    public static void valueChangeListener(FormFieldView view, final InverseBindingListener listener) {
        if (view.fieldType == 0) {
            view.etInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (listener != null) {
                        listener.onChange();
                    }
                }
            });
        } else {
            view.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    if (listener != null) {
                        listener.onChange();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {
                    if (listener != null) {
                        listener.onChange();
                    }
                }
            });
        }
    }

    // 设置输入值
    public void setValue(String value) {
        if (fieldType == 0) {
            etInput.setText(value);
        } else {
            if (spinner.getAdapter() != null) {
                for (int i = 0; i < spinner.getAdapter().getCount(); i++) {
                    if (spinner.getAdapter().getItem(i).toString().equals(value)) {
                        spinner.setSelection(i);
                        break;
                    }
                }
            }
        }
    }

    // 设置标签
    public void setLabel(String label) {
        this.label = label;
        tvLabel.setText(label);
    }

    // 设置字段类型
    public void setFieldType(int type) {
        this.fieldType = type;
        applyAttributes();
    }

    // 设置是否可编辑
    public void setEditable(boolean editable) {
        this.editable = editable;
        if (fieldType == 0) {
            etInput.setEnabled(editable);
            etInput.setFocusable(editable);
            etInput.setFocusableInTouchMode(editable);
        } else {
            spinner.setEnabled(editable);
        }
    }

    // 设置下拉选项
    public void setSpinnerEntries(int arrayResId) {
        this.spinnerEntriesResId = arrayResId;
        if (fieldType == 1) {
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    getContext(),
                    arrayResId,
                    android.R.layout.simple_spinner_item
            );
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
        }
    }

    // 设置提示文本
    public void setHint(String hint) {
        this.hint = hint;
        if (fieldType == 0) {
            etInput.setHint(hint);
        }
    }
}